/**
 * @author mapeng
 * @version 2017-05-09
 */

(function(doc, win) {

	var pageVariables = {
		"submitData" : {},
		"timer" : ""
	};

	$(doc).on("pageInit", "#weixinOpenMobileVerifyPage4Wangshang", function(e, pageId, $page, isBack,isForward) {
		if(isBack || isForward)	return;

		init4Page();
	});
	bindEvents4Page();

	//页面初始化
	function init4Page(){

		//获取参数
		var params = CommonUtil.takeOutParamObject() || {};
		pageVariables.submitData = params.submitData;
		$("#weixinOpenMobileVerifyPage4Wangshang input[name='accounterMobile']").val(pageVariables.submitData.principalMobile);

		pageVariables.timer = "";
	}

	//绑定事件
	function bindEvents4Page(){

		//返回：取消定时器
		$(document).on("click","#weixinOpenMobileVerifyPage4Wangshang .header a[name='back']",function(e){
			if(pageVariables.timer){
				endSeconds4WeixinSafeVerifyPage($("#weixinOpenMobileVerifyPage4Wangshang span.get-code"));
				pageVariables.timer = "";
			}
			$.router.back();
		});

		//发送验证码
		$(document).on("click","#weixinOpenMobileVerifyPage4Wangshang span.get-code",function(e){

			var $this = $(this);

			if($this.hasClass("disabled"))	return;

			//加入缓存，一分钟内同一商户不允许再次发送验证码
			var smsCache = localStorageClient.load("sms4wangshang",1);
			log4JS.info("sms4Wangshang = " + smsCache);
			if(smsCache){
				DialogUtil.dialogWarn("您操作太频繁，请一分钟后重试");
				return;
			}

			CommonUtil.sendJsonpRequest({
			// apiTest.testSendVerifyCode({
				"url" : App.serverUrl + "/app/wxAccountCloudBox/sendVerifyCode4Ant.do",
				"params" : {"mobile" : pageVariables.submitData.principalMobile},
				"success" : function(result){
					if(result.success.toString() == "true"){//success
						DialogUtil.dialogWarn("发送成功");
						readSeconds4WeixinSafeVerifyPage($this,60);

						//加入缓存，一分钟内同一商户不允许再次发送验证码
						localStorageClient.save("sms4wangshang","1",true);

					}else{//business error
						DialogUtil.dialogWarn(result.msg);
					}
				},
				"error" : function(){//not 200
					DialogUtil.dialogWarn("请求失败，请稍候重试");
				}
			});
		});

		//验证
		$(document).on("click","#weixinOpenMobileVerifyPage4Wangshang .header a[name='verify']",function(e){
			
			var verifyCode = $("#weixinOpenMobileVerifyPage4Wangshang input[name='verifyCode']").val();
			if(!/^[0-9]{6}$/.test(verifyCode)){
				DialogUtil.dialogWarn("请您输入六位数字验证码");
				return;
			}

			//连同验证码一起提交开通微信支付
			common.loading("提交中");
			AppUtil.call(
			// apiTest.testSubmit(
				AppUtil.APIS.SEND_HTTP_REQUEST,
				{
					"type":"POST",
					"url":App.serverUrl + "/app/wxAccountCloudBox/apply.do",
					"data":JSON.stringify($.extend({},pageVariables.submitData,{"authCode" : verifyCode}))
				},
				function(submitResult){
					common.closeLoading();

					//清除倒计时
					if(pageVariables.timer){
						endSeconds4WeixinSafeVerifyPage($("#weixinOpenMobileVerifyPage4Wangshang span.get-code"));
						pageVariables.timer = "";
					}

					var cache = CommonUtil.takeOutParamObject() || {};
					cache.shopId = pageVariables.submitData.shopId;
					CommonUtil.injectParamObject(cache);

					if(submitResult.success.toString() == "true" && submitResult.resultObject.success.toString() == "true"){//成功
						$.router.load("weixin_open_success_wangshang.html");
					}else{//失败
						var errorMsg = "";
						if(submitResult.success.toString() == "false"){
							errorMsg = submitResult.msg;
						}else if(submitResult.resultObject.success.toString() == "false"){
							errorMsg = submitResult.resultObject.msg;
						}
						
						var cache = CommonUtil.takeOutParamObject() || {};
						cache.errorMsg = errorMsg;
						CommonUtil.injectParamObject(cache);
						$.router.load("weixin_open_error_wangshang.html");
					}
				}
			);
		});
	}

	/**
	 * 读秒
	 * @param  {[jquery obj]} $obj    目标对象
	 * @param  {[int]} waitTime 秒数
	 */
	function readSeconds4WeixinSafeVerifyPage($obj,waitTime){
		var waitTime = waitTime ? waitTime : 60;
        var countdown = waitTime;
        settime($obj);
        function settime(val) {
            if (countdown == 0) {
                val.removeClass("disabled");
                val.text("重新发送");
                countdown = waitTime;
                clearTimeout(pageVariables.timer);
                pageVariables.timer = "";
            } else {
                val.addClass("disabled");
                val.text(countdown + "秒后重发");
                countdown--;
                pageVariables.timer = setTimeout(function () {
                    settime(val);
                }, 1000)
            }
        }
	}

	/**
	 * 结束读秒
	 * @param  {[type]} $obj  目标对象
	 * @param  {[type]} timer 定时器
	 */
	function endSeconds4WeixinSafeVerifyPage($obj){
		$obj.removeClass("disabled");
		$obj.text("获取验证码");
		clearTimeout(pageVariables.timer);
		pageVariables.timer = "";
	}

	/**
	 * 测试接口
	 * @type {Object}
	 */
	var apiTest = {
		"testSendVerifyCode" : function(options){//发送验证码
			options.success({
				"success" : true
			});
		},
		"testSubmit" : function(apiName,params,callback){//提交
			callback({
				"code" : "0",
				"msg" : "",
				"resultObject" : {
					"code" : "0",
					"msg" : "参数不正确",
					"success" : true,
					"resultObject" : ""
				},
				"success" : true
			});
		}
	};

})(document, window);